package com.taxi.driver.module.order.price;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.qianxx.utils.PhoneUtils;
import com.qianxx.utils.TypeUtils;
import com.qianxx.view.HeadView;
import com.qianxx.view.dialog.ExSweetAlertDialog;
import com.taxi.driver.R;
import com.taxi.driver.common.AppConfig;
import com.taxi.driver.common.BaseActivity;
import com.taxi.driver.config.BizStatus;
import com.taxi.driver.config.IConstants;
import com.taxi.driver.data.entity.OrderCostEntity;
import com.taxi.driver.event.OrderEvent;
import com.taxi.driver.module.order.detail.OrderDetailActivity;
import com.taxi.driver.module.order.price.dagger.DaggerPriceCheckComponent;
import com.taxi.driver.module.order.price.dagger.PriceCheckModule;
import com.taxi.driver.module.vo.PassengerVO;
import com.taxi.driver.module.web.WebActivity;
import com.taxi.driver.socket.SocketEvent;
import com.taxi.driver.util.PointFilter;
import com.taxi.driver.widget.CircleImageView;
import com.taxi.driver.widget.ImageViewPlus;
import com.taxi.driver.widget.SlideView;
import com.taxi.driver.widget.TextViewPlus;
import com.taxi.driver.widget.dialog.TwoSelectorDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Locale;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTouch;

import static org.litepal.LitePalApplication.getContext;

/**
 * 功能描述：(专车)费用确认页
 */
public class PriceCheckActivity extends BaseActivity implements PriceCheckContract.View {
    static OrderDetailActivity  mActivity;
    public static void actionStart(OrderDetailActivity orderDetailActivity, String ordeUuid, PassengerVO passengerVO) {
//        mContext=context;
        Intent intent = new Intent(orderDetailActivity, PriceCheckActivity.class);
        intent.putExtra(IConstants.ORDER_UUID, ordeUuid);
        if (passengerVO != null) {
            intent.putExtra(IConstants.PARAMS, passengerVO);
        }
        mActivity=orderDetailActivity;
        orderDetailActivity.startActivity(intent);
    }

    @BindView(R.id.head_view)
    HeadView mHeadView;
    @BindView(R.id.iv_avatar)
    CircleImageView mIvAvatar;
    @BindView(R.id.tv_info)
    TextView mTvInfo;
    @BindView(R.id.iv_phone)
    ImageViewPlus mIvPhone;
    @BindView(R.id.tv_price)
    TextView mTvPrice;
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.tv_rule)
    TextViewPlus mTvRule;
    @BindView(R.id.tv_error)
    TextView mTvError;
    @BindView(R.id.slide_view)
    SlideView mSlideView;
    @BindView(R.id.et_highspeed)
    EditText mEtHighspeed;
    @BindView(R.id.rl_highspeed)
    RelativeLayout mRlHighspeed;
    @BindView(R.id.et_parking)
    EditText mEtParking;
    @BindView(R.id.rl_parking)
    RelativeLayout mRlParking;
    @BindView(R.id.et_other)
    EditText mEtOther;
    @BindView(R.id.rl_other)
    RelativeLayout mRlOther;

    @Inject
    PriceCheckPresenter mPresenter;

    private PassengerVO mPassengerVO;
    private PriceDetailAdapter mAdapter;
    private String mOrderUuid;
//    private String mCurrentCity;
    private double mHighSpeedFee;
    private double mParkingFee;
    private double mOtherFee;
    private double totalFee;
    //司机是否已经确认订单;默认 没有确认
    private boolean  isConfirm=false;
    private Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_price_check);
        ButterKnife.bind(this);
        handler=new Handler();
        mHeadView.setLeftVisibility(false);
        DaggerPriceCheckComponent.builder()
                .appComponent(getAppComponent())
                .priceCheckModule(new PriceCheckModule(this))
                .build()
                .inject(this);
        mOrderUuid = getIntent().getStringExtra(IConstants.ORDER_UUID);
        mPresenter.setOrderUuid(mOrderUuid);
//        mPresenter.getCurrentCity();
        initAdapter();
        mPassengerVO = (PassengerVO) getIntent().getSerializableExtra(IConstants.PARAMS);
        showPassengerInfo(mPassengerVO);

        initEditText();
        mSlideView.setOnSlideListener(() -> {

            mPresenter.confirmFare(mHighSpeedFee == 0d ? null : (int) mHighSpeedFee,
                    mParkingFee == 0d ? null : (int) mParkingFee,
                    mOtherFee == 0d ? null : (int) mOtherFee); //确认费用
            isConfirm=true;
        });
        handler.postDelayed(runnable,1000*60*10); //延时10M执行

    }
    Runnable  runnable =new Runnable() {
        @Override
        public void run() {
            if (!isConfirm){
                mPresenter.confirmFare(mHighSpeedFee == 0d ? null : (int) mHighSpeedFee,
                        mParkingFee == 0d ? null : (int) mParkingFee,
                        mOtherFee == 0d ? null : (int) mOtherFee); }
        }
    };
    private void initAdapter() {
        mAdapter = new PriceDetailAdapter(this, R.layout.item_order_cost);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(mAdapter);
    }

    private void initEditText() {
        mEtHighspeed.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String str = s.toString().trim();
                double money;
                if (str.length() <= 0) {
                    mHighSpeedFee = 0;
                } else {
                    mHighSpeedFee = Integer.parseInt(str);
                }
                money = totalFee + mHighSpeedFee + mParkingFee + mOtherFee;
                mTvPrice.setText(String.format(Locale.CHINA, "%.01f", money) + "元");
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        mEtParking.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String str = s.toString().trim();
                double money;
                if (str.length() <= 0) {
                    mParkingFee = 0;
                } else {
                    mParkingFee = Integer.parseInt(str);
                }
                money = totalFee + mHighSpeedFee + mParkingFee + mOtherFee;
                mTvPrice.setText(String.format(Locale.CHINA, "%.01f", money) + "元");
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        mEtOther.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String str = s.toString().trim();
                double money;
                if (str.length() <= 0) {
                    mOtherFee = 0;
                } else {
                    mOtherFee = Integer.parseInt(str);
                }
                money = totalFee + mHighSpeedFee + mParkingFee + mOtherFee;
                mTvPrice.setText(String.format(Locale.CHINA, "%.01f", money) + "元");
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        mEtHighspeed.setFilters(new InputFilter[]{new PointFilter()});
        mEtParking.setFilters(new InputFilter[]{new PointFilter()});
        mEtOther.setFilters(new InputFilter[]{new PointFilter()});
    }

    @Override
    protected void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
        mPresenter.subscribe();
    }

    @Override
    protected void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
        mPresenter.unsubscribe();
    }

    @Override
    public boolean isActive() {
        return false;
    }

    @Override
    public void onBackPressed() {

    }


    @OnClick({R.id.iv_phone, R.id.tv_rule, R.id.tv_error, R.id.rl_highspeed, R.id.et_highspeed, R.id.rl_parking, R.id.rl_other})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_phone:
                PhoneUtils.skip(getContext(), mPassengerVO == null ? "" : TypeUtils.getValue(mPassengerVO.mobile));
                break;
            case R.id.tv_rule:
                String rulesUrl = AppConfig.HOST
                        + mPresenter.getPriceRule() + "&orderUuid=" + mOrderUuid;
                if (TextUtils.isEmpty(rulesUrl)) {
                    toast("未获取到计价规则");
                    return;
                }
                WebActivity.actionStart(this, rulesUrl, "计价规则");
                break;
            case R.id.tv_error:

                new TwoSelectorDialog(this, "若您或乘客对费用有异议,可协商后联系客服进行修改。", null,
                        "取消", "联系客服").setConfirmClickListener(new ExSweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(ExSweetAlertDialog sweetAlertDialog) {
                        if (sweetAlertDialog != null)
                            sweetAlertDialog.dismiss();
                        PhoneUtils.skip(getContext(), R.string.contact_phone);
//                        if (mCurrentCity.equals("天津市")){
//                            PhoneUtils.skip(getContext(), R.string.contact_phone_tianjing);
//                        }else{
//                            PhoneUtils.skip(getContext(), R.string.contact_phone_other);
//                        }
                    }
                }).setCancelClickListener(sweetAlertDialog ->
                {
                    if (sweetAlertDialog != null)
                        sweetAlertDialog.dismiss();
                }).show();
                break;
            case R.id.rl_highspeed:
                setEditBack(true, false, false);
                break;
            case R.id.rl_parking:
                setEditBack(false, true, false);
                break;
            case R.id.rl_other:
                setEditBack(false, false, true);
                break;
        }
    }

    @Override
    public void showPassengerInfo(PassengerVO vo) {
        if (vo == null) return;
        if (!TextUtils.isEmpty(vo.face)) Glide.with(this).load(vo.face).into(mIvAvatar);
        String phoneEnd = vo.getPassengerPhoneEnd();
        mTvInfo.setText(TextUtils.isEmpty(phoneEnd) ? "" : "尾号" + phoneEnd);
    }

    @Override
    public void setDisplay(OrderCostEntity entity) {
        double money;
        totalFee = entity.totalFare;
        money = totalFee + mHighSpeedFee + mParkingFee + mOtherFee;
        mTvPrice.setText(String.format(Locale.CHINA, "%.01f", money) + "元");
        mAdapter.setAll(entity.costItems);
    }

    @Override
    public void confirmFareSuccess() {
        // 营运状态（空驶）
        EventBus.getDefault().post(new SocketEvent(SocketEvent.BIZ_STATUS, BizStatus.EMPTY_DRIVING));
//        OrderDetailActivity.
        finish(); //关闭界面
        if (!isConfirm){
            mActivity.finish();
        }

    }

    @Override
    public void resetBtnDisplay() {
        mSlideView.resetView();
    }

//    @Override
//    public void getCurrentCity(String city) {
//        mCurrentCity=city;
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onOrderEvent(OrderEvent event) {
        switch (event.type) {
            case OrderEvent.MODIFY_MONEY:
                // 重新获取费用明细
                mPresenter.reqFareItems();
                break;
        }
    }

    @OnTouch(value = {R.id.et_highspeed, R.id.et_parking, R.id.et_other})
    public boolean onTouch(View view, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            switch (view.getId()) {
                case R.id.et_highspeed:
                    setEditBack(true, false, false);
                    break;
                case R.id.et_parking:
                    setEditBack(false, true, false);
                    break;
                case R.id.et_other:
                    setEditBack(false, false, true);
                    break;
            }
        }
        return false;
    }

    private void setEditBack(boolean isHighSpeed, boolean isParking, boolean isOther) {
        mRlHighspeed.setSelected(isHighSpeed);
        mRlParking.setSelected(isParking);
        mRlOther.setSelected(isOther);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(runnable);
    }
}
